package com.android.base_network

import com.aleyn.cache.CacheManager
import com.aleyn.cache.NetCacheInterceptor
import com.android.base_network.adapter.FlowAdapterFactory
import com.android.base_network.interceptor.AddHeadParamsInterceptor
import com.android.base_network.interceptor.ResponseInterceptor
import com.android.base_network.interceptor.TokenInterceptor
import com.blankj.utilcode.util.Utils
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitClient {

    companion object {
        fun getInstance() = SingleHolder.instance
        private lateinit var retrofit: Retrofit

        private const val timeout = 20L
    }

    private object SingleHolder {
        val instance = RetrofitClient()
    }

    init {
        retrofit = Retrofit.Builder()
            .client(getOkhttpClient())
            .addCallAdapterFactory(FlowAdapterFactory.create(true))
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BuildConfig.base_url)
            .build()
    }

    private fun getOkhttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(timeout, TimeUnit.SECONDS)
            .writeTimeout(timeout, TimeUnit.SECONDS)
            .readTimeout(timeout, TimeUnit.SECONDS)
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
            .addInterceptor(AddHeadParamsInterceptor())
            .addInterceptor(ResponseInterceptor())
            .addInterceptor(NetCacheInterceptor(CacheManager(Utils.getApp().cacheDir)))
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            .addInterceptor(TokenInterceptor())
            .build()
    }

    fun <T> createApi(service: Class<T>): T = retrofit.create(service)
}